package com.bjpowernode.config.handler;

import com.bjpowernode.constant.Constants;
import com.bjpowernode.model.TUser;
import com.bjpowernode.result.R;
import com.bjpowernode.service.RedisService;
import com.bjpowernode.util.JSONUtil;
import com.bjpowernode.util.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出成功的handler
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        //返回json

        //设置响应编码
        response.setCharacterEncoding("UTF-8");
        //设置响应内容类型(媒体类型)
        response.setContentType("application/json;charset=utf-8");

        //退出的时候，需要把redis的jwt删除
        TUser tUser = (TUser) authentication.getPrincipal();
        redisService.remove(Constants.REDIS_LOGIN_JWT_KEY + tUser.getId());

        //返回JSON出去
        R result = new R(200,"退出成功", null);

        //把result对象转成JSON
        String json = JSONUtil.toJSON(result);

        //结果写出去
        ResponseUtil.write(response, json);
    }
}
